<template>
  <div style="width: 100%; height: 100%; position: relative;">
    <div ref="chartRef" style="width: 100%; height: 100%;"></div>

    <!-- 轮换状态指示器 -->
<!--    <div class="rotation-indicator" :class="{ 'showing-total': isShowingTotal, 'showing-density': !isShowingTotal }">-->
<!--      <div class="indicator-dot" :class="{ 'active': isShowingTotal }"></div>-->
<!--      <div class="indicator-dot" :class="{ 'active': !isShowingTotal }"></div>-->
<!--      <div class="indicator-text">{{ isShowingTotal ? 'GEP总值' : 'GEP地均' }}</div>-->
<!--    </div>-->
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import { useHomepageStore } from '@/stores/homepage';
import { townToProjectTownAreaMap } from '@/utils/areaMapping';

// 定义数据类型
interface ChartDataItem {
  name: string;
  value: number;
}

// 使用 homepage store
const homepageStore = useHomepageStore();
const year = homepageStore.getYear;

// 轮换状态管理
const isShowingTotal = ref(true); // true: 显示总值, false: 显示地均
let rotationTimer: any = null;

// 数据处理 - 添加默认值
// const rawData = computed<ChartDataItem[]>(() => {
//   console.log('原始数据', homepageStore.chartData);
//   return homepageStore.chartData?.bar01 || [];
// });
const rawData = computed<ChartDataItem[]>(() => {
  console.log('原始数据', homepageStore.chartData);

  // 如果 homepageStore.chartData?.bar01 存在且为数组，则处理
  if (homepageStore.gepResults?.towns && homepageStore.gepResults.towns.length > 0 ) {
    return homepageStore.gepResults.towns.map(item => {
      // 将字符串转换为数字并求和
      const material = parseFloat(item.material) || 0;
      const culture = parseFloat(item.culture) || 0;
      const regulation = parseFloat(item.regulation) || 0;

      return {
        name: item.name,
        value: material + culture + regulation
      };
    });
  }

  // 否则返回空数组
  return [];
});



// 计算地均GEP数据
const densityData = computed<ChartDataItem[]>(() => {
  // 确保数据存在再进行处理
  if (rawData.value && Array.isArray(rawData.value)) {
    // 计算地均值（GEP总值/面积）
    const density = rawData.value.map(item => {
      const area = townToProjectTownAreaMap[item.name] || 1; // 防止除以0
      return {
        name: item.name,
        value: item.value / area // 计算地均值
      };
    });
    console.log('地均数据已计算并排序', [...density].sort((a, b) => b.value - a.value))
    return [...density].sort((a, b) => b.value - a.value);
  }
  console.log('返回空数组作为默认值', []);
  return []; // 返回空数组作为默认值
});

// 当前显示的数据
const data = computed<ChartDataItem[]>(() => {
  if (isShowingTotal.value) {
    // 显示总值数据
    return rawData.value && Array.isArray(rawData.value)
        ? [...rawData.value].sort((a, b) => b.value - a.value)
        : [];
  } else {
    // 显示地均数据
    return densityData.value;
  }
});

// 轮换函数
const rotateData = () => {
  if (chart) {
    // 添加淡出动画
    chart.setOption({
      animation: true,
      animationDuration: 500,
      animationEasing: 'cubicOut'
    });

    // 延迟切换数据，让淡出动画先执行
    setTimeout(() => {
      isShowingTotal.value = !isShowingTotal.value;
      if (chart) {
        chart.setOption(getOption());

        // 添加淡入动画
        chart.setOption({
          animation: true,
          animationDuration: 800,
          animationEasing: 'cubicInOut'
        });
      }
    }, 300);
  }
};

// 启动轮换定时器
const startRotation = () => {
  if (rotationTimer) {
    clearInterval(rotationTimer);
  }
  rotationTimer = setInterval(rotateData, 9000); // 每3秒轮换一次
};

// 停止轮换定时器
const stopRotation = () => {
  if (rotationTimer) {
    clearInterval(rotationTimer);
    rotationTimer = null;
  }
};

// 辅助函数 - 添加类型检查
const getArrByKey = (data: ChartDataItem[], k?: string): any[] => {
  const key = k || "value";
  const res: any[] = [];
  if (data && Array.isArray(data)) {
    data.forEach(function (t) {
      res.push(t[key]);
    });
  }
  return res;
};

const getYAxisData = (data: ChartDataItem[]): string[] => {
  if (!data || !Array.isArray(data)) return [];
  return data.map((item, index) => `${index + 1} ${item.name}`);
};

const getSymbolData = (data: ChartDataItem[]): { value: number; symbolPosition: string }[] => {
  const arr: { value: number; symbolPosition: string }[] = [];
  if (data && Array.isArray(data)) {
    for (let i = 0; i < data.length; i++) {
      arr.push({
        value: data[i].value,
        symbolPosition: 'end'
      });
    }
  }
  return arr;
};

// ECharts 容器引用
const chartRef = ref<HTMLElement | null>(null);
let chart: echarts.ECharts | null = null;

// 将 option 改为一个函数
const getOption = (): echarts.EChartsOption => ({
  // 全局动画配置
  animation: true,
  animationDuration: 1000,
  animationEasing: 'cubicInOut',
  animationDelay: (idx: number) => idx * 100, // 每个柱子依次动画

  title: {
    text: isShowingTotal.value ? '———'+homepageStore.getYear+'总值' : '———'+homepageStore.getYear+'地均',
    textStyle: {
      color: '#9f9f9f',
      fontSize: 12
    },
    left: 'right'
  },
  tooltip: {
    trigger: 'item',
    formatter: (params: any) => {
      // 排名系列（pictorialBar）
      if (params.seriesName === 'top-point') {
        return `${params.marker} ${params.name} 排名: 第 ${params.dataIndex + 1} 名`;
      }
      // GEP系列（bar）
      if (params.seriesName === '条') {
        if (isShowingTotal.value) {
          // 总值数据
          const value = params.value / 10000; // 转换为亿元
          return `${params.marker} ${params.name} GEP总值: <strong>${value.toFixed(2)} 亿元</strong>`;
        } else {
          // 地均数据
          const value = params.value / 100;
          return `${params.marker} ${params.name} GEP地均: <strong>${value.toFixed(2)} 元/m2</strong>`;
        }
      }

      return params.name; // 默认返回名称
    },
    backgroundColor: 'rgba(255,255,255,0.9)',
    borderColor: '#666',
    textStyle: {
      fontSize: 14,
      fontWeight: 'normal'
    }
  },
  grid: {
    top: '4%',
    bottom: -15,
    right: 10,
    left: 10,
    containLabel: true
  },
  xAxis: {
    show: false
  },
  yAxis: [{
    triggerEvent: true,
    show: true,
    inverse: true,
    data: getYAxisData(data.value),
    axisLine: {
      show: false
    },
    splitLine: {
      show: false
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      show: false,
      interval: 0,
      color: '#fff',
      align: 'left',
      verticalAlign: 'middle',
      margin: 80,
      fontSize: 13,
    },
  },
    {
      triggerEvent: true,
      show: true,
      inverse: true,
      data: getArrByKey(data.value, 'name'),
      axisLine: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        interval: 0,
        color: '#fff',
        align: 'right',
        verticalAlign: 'bottom',
        lineHeight: 30,
        fontSize: 16,
        formatter: function (value: string, index: number) {
          if (!data.value[index]) return '';
          if (isShowingTotal.value) {
            // 总值数据
            const res = data.value[index].value / 10000; // 转换为亿元
            return res.toFixed(2) + ' 亿元';
          } else {
            // 地均数据
            const res = data.value[index].value / 100;
            return res.toFixed(2) + ' 元/m2';
          }
        },
      }
    }],
  series: [{
    name: 'top-point',
    type: 'pictorialBar',
    symbol: 'image://',
    symbolSize: [50, 50],
    symbolOffset: [27, -8],
    z: 12,
    data: getSymbolData(data.value),
    // 排名图标动画
    animation: true,
    animationDuration: 1200,
    animationEasing: 'bounceOut',
    animationDelay: (idx: number) => idx * 150
  } as echarts.PictorialBarSeriesOption, {
    name: '条',
    type: 'pictorialBar',
    symbol: 'path://M0,50 L100,0 L100,100 Z',
    showBackground: true,
    barBorderRadius: 30,
    yAxisIndex: 0,
    data: data.value.map(item => item.value),
    barWidth: 10,
    itemStyle: {
      color: new echarts.graphic.LinearGradient(
          0,
          0,
          1,
          0,
          [{
            offset: 0,
            color: '#279791FF'
          },
            {
              offset: 0.7,
              color: '#279791FF'
            },
            {
              offset: 1,
              color: '#5EDEE5'
            }],
          false
      ),
      barBorderRadius: 10
    },
    label: {
      color: '#fff',
      show: true,
      position: [0, '-20px'],
      textStyle: {
        fontSize: 16
      },
      distance: 5,
      formatter: function (a: any) {
        return a.name;
      },
      // 标签动画
      animation: true,
      animationDuration: 800,
      animationEasing: 'elasticOut',
      animationDelay: (idx: number) => idx * 120
    },
    // 柱状图动画
    animation: true,
    animationDuration: 1500,
    animationEasing: 'cubicInOut',
    animationDelay: (idx: number) => idx * 100,
    // 添加缩放动画
    animationDurationUpdate: 1000,
    animationEasingUpdate: 'cubicInOut'
  } as echarts.PictorialBarSeriesOption]
});

// 监听数据变化，更新图表
watch(data, () => {
  if (chart) {
    chart.setOption(getOption());
  }
});

// 监听轮换状态变化
watch(isShowingTotal, () => {
  if (chart) {
    chart.setOption(getOption());
  }
});

// 初始化 ECharts 实例
onMounted(() => {
  setTimeout(() => {
    if (chartRef.value) {
      chart = echarts.init(chartRef.value);
      chart.setOption(getOption()); // 调用函数获取最新配置
      // 启动轮换
      startRotation();
    }
  }, 200);
});

// 组件卸载时清理定时器
onUnmounted(() => {
  stopRotation();
});
</script>

<style scoped>

</style>
